import { Button, Checkbox, Form, Input,Card  } from 'antd';
import React from 'react';
import {useNavigate} from 'react-router-dom'
import {adminnameExist,register} from '../../services/admin'

const Login = () => {
  const navigate = useNavigate();
  const onFinish =async (values) => {
    let {username,password} = values
    let result = await register({
      adminName:username,
      adminPassword:password
    })
    if(result.code ==='0') navigate('/login');
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <Card title="注册"  style={{ width: 500 ,margin:'auto',marginTop:'10%'}}>
    <Form
      name="basic"
      labelCol={{
        span: 6,
      }}
      wrapperCol={{
        span: 12,
      }}
      initialValues={{
        remember: true,
      }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item
      hasFeedback
        label="用户名"
        name="username"
        rules={[
          {
            required: true,
            message: '用户名不能为空...',
          },{
            pattern: /\w{4,20}/,
            message: '格式不正确...',
          },{
            async validator(_, value) {
              let result = await adminnameExist(value)
              // console.log(result)
              if (result.code === '0') {
                return Promise.resolve();
              }
              return Promise.reject(new Error('账号已存在'));
            }
          }
        ]}
      >
        <Input />
      </Form.Item>

      <Form.Item
      hasFeedback
        label="密码"
        name="password"
        rules={[
          {
            required: true,
            message: '密码不能为空...',
          },{
            pattern: /\w{6,20}/,
            message: '格式不正确...',
          }
        ]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item
      hasFeedback
        label="确认密码"
        name="confirm"
        rules={[
          {
            required: true,
            message: '确认密码不能为空...',
          },({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('password') === value) {
                return Promise.resolve();
              }

              return Promise.reject(new Error('确认密码必须和密码保持一致！'));
            }
          })
        ]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item
        name="remember"
        valuePropName="checked"
        wrapperCol={{
          offset: 8,
          span: 16,
        }}
      >
        <Checkbox>Remember me</Checkbox>
      </Form.Item>

      <Form.Item
        wrapperCol={{
          offset: 8,
          span: 16,
        }}
      >
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
    </Card>
  );
};

export default Login;